/*

	仪器销售政策任务量拆分 


*/
public without sharing class TaskPolicyDivideController {
    
	public Boolean isErr {get ; set;}

	public String msg {get; private set;}
	public Boolean isSuccess {get; private set;}

	public String  ipId {get; private set;}
	public String dataJson {get; private set;}
	public String saveJson {get;  set;}

	private InstrumentPolicy__c insp ; 
	public String backId {get; private set;}
	private List<InstrumentMarketingPolicy__c> impList ; 
	public class ControllerException extends Exception {}


    public TaskPolicyDivideController() {
    	ipId  = System.currentPageReference().getParameters().get('id');
    	impList = new List<InstrumentMarketingPolicy__c>();
    }
    public void setNil(){
    	dataJson = '[]';
    	saveJson = '[]';
    }
    public void init(){

    	try {
    	  	if(ipId == null)setErr('页面打开错误!');  
    	  	if(Id.valueOf(ipId).getSobjectType() !=  InstrumentPolicy__c.SObjectType)setErr('页面打开错误!'); 
    	  
    	  	insp = [select Id , Account__c  , TerminalCustomer__c ,Status__c from InstrumentPolicy__c where id=:ipId];
    	  	backId = ipId;
    	  	if(insp.Status__c != '已批准' )setErr('未审批通过不能拆分!');

    	}catch (Exception e) {

    	     ApexPages.addMessage( new ApexPages.Message(ApexPages.Severity.ERROR ,e.getMessage()));

    	}
    	

    }
    public void getDetails(){
    	List<PolicyBean> tmp = new List<PolicyBean>();
    	  for(InstrumentMarketingPolicy__c imp : [select Id,AmountPurchasedZN__c, ReturnServiceFee__c,
    	   ReturnServiceFeeRentalFee__c ,Quantity__c,RentalFee__c ,Category1__c,Category2__c,Brand__c,
    	   CooperationPeriod__c,AmountPurchased__c,
    	   DevidedEquipNum__c,MarketingPolicy__r.Product__c, MarketingPolicy__r.Product__r.ProductName__c  from InstrumentMarketingPolicy__c where InstrumentPolicy__c =: ipId]){
    	  		
    	  		tmp.add(new PolicyBean(imp));
    	  		impList.add(imp);

    	  }
    	  dataJson = EncodingUtil.urlEncode(JSON.serialize(tmp), 'UTF-8');
    }
    private void setErr(String message){
    	isErr  =true;
    	throw new ControllerException(message);
    }
    private Decimal getDecimalValue(Object o ){
    	if(o == null )return null;
    	String d = String.valueOf(o).trim();
    	if(d == '')return null;
    	return Decimal.valueOf(d);
    }
    private String getStringVlaue(Object o ){
    	if( o == null ) return  null; 
    	return String.valueOf(o).trim();
    }
    public void saveData(){
    	msg = '';
    	List<Object> resList = (List<Object>)JSON.deserializeUntyped(EncodingUtil.urlDecode(saveJson, 'UTF-8'));

    	if(resList.size() == 0){
    		msg = '没有数据!';
    		return;
    	}
    	Date minStartDate = null;
    	Map<String , Decimal > numMap = new Map<String ,Decimal>();
    	List<TaskAmount__c> taList = new List<TaskAmount__c>();
    	for (Object o  :resList) {
    		Map<String,Object> mo = (Map<String,Object>) o ; 

    		if(getDecimalValue(mo.get('num')) == null || getDecimalValue(mo.get('num')) == 0  ){
    			msg = '拆分台数不能为空!';
    			return;

    		}
    		if(getStringVlaue(mo.get('startDate')) == null || getStringVlaue(mo.get('startDate')) == ''){
    			msg = '合作开始日期不能为空!';
    			return ;
    		}

    		if(getDecimalValue(mo.get('num')) + getDecimalValue(mo.get('devNum')) > getDecimalValue(mo.get('total'))){
    			msg = '拆分台数不能超过剩余数量!';
    			return;
    		}

    		Date sd = Date.valueOf(getStringVlaue(mo.get('startDate')));
            minStartDate =  (  minStartDate == null ? sd : (   minStartDate.daysBetween(sd) > 0 ? minStartDate : sd  )  ) ;

    		Integer cy = Integer.valueOf(getStringVlaue(mo.get('coopyear')));
    		Decimal num =  getDecimalValue(mo.get('num'));
    		Decimal amount = getDecimalValue(mo.get('amount'));
    		String cate1 = getStringVlaue(mo.get('cate1'));
    		String cate2 = getStringVlaue(mo.get('cate2'));
    		String brand = getStringVlaue(mo.get('brand'));
    		String impId = getStringVlaue(mo.get('impId'));
    		Decimal returnServiceFee = getDecimalValue(mo.get('returnServiceFee'));
    		Decimal returnServiceFeeRentalFee = getDecimalValue(mo.get('returnServiceFeeRentalFee'));
    		numMap.put(impId, num);
    		Decimal subprofit  =  getDecimalValue(mo.get('subprofit'));
    		Decimal groupprofit   =  getDecimalValue(mo.get('groupprofit'));


        	for(Integer i = 0 ; i <  cy * 12 ; i ++){

        		TaskAmount__c ta = new TaskAmount__c();

        		ta.AssignAmount__c = amount * num / 12  / 10000.0;
                ta.ReturnServiceFee__c = returnServiceFee * num / 12 ;
                ta.ReturnServiceFeeRentalFee__c =  returnServiceFeeRentalFee * num / 12 ;
                ta.SubProfit__c = subprofit * num / 12 /10000.0 ;
                ta.GroupProfit__c = groupprofit * num / 12 /10000.0 ; 

        		Date  d = sd.addMonths(i);

        		ta.Year__c = String.valueOf(d.year())+'年';
        		ta.Month__c = String.valueOf(d.month());
        		ta.Origin__c = '销售政策';
        		ta.Category1__c = cate1  ;
        		ta.Category2__c = cate2  ;
        		ta.Brand__c = brand ;
        		ta.EquipmentPolicy__c = impId;
        		taList.add(ta);

        	}

    	}

    	 //找到任务量追踪总表; 无则 新建任务量追踪总表
        CooperationStandard__c cs  = null ;
        try{
            cs =  [select Id ,StartingDate__c  from CooperationStandard__c  where NewData__c = true 
            and Account__c =:insp.Account__c and TerminalCustomer__c =:insp.TerminalCustomer__c ]; 
        }catch(Exception e){
            cs =  new CooperationStandard__c();
            cs.Account__c = insp.Account__c;
            cs.TerminalCustomer__c = insp.TerminalCustomer__c;
            cs.NewData__c = true; //标记是新生成的任务量主表
        }

        cs.StartingDate__c = cs.StartingDate__c == null ?  minStartDate : (minStartDate.daysBetween(cs.StartingDate__c) > 0 ? minStartDate : cs.StartingDate__c );
        SavePoint sp = Database.setSavepoint();

        ///更新拆分数量
        List<InstrumentMarketingPolicy__c> tmp = new List<InstrumentMarketingPolicy__c>();
        for (InstrumentMarketingPolicy__c imp : impList) {
        	if(numMap.containsKey(imp.Id)){
        		imp.DevidedEquipNum__c = imp.DevidedEquipNum__c == null  ? numMap.get(imp.Id ) : imp.DevidedEquipNum__c + numMap.get(imp.Id ) ;
        		tmp.add(imp);
        	}
        }
        try {
            
            upsert cs ; 
            for (TaskAmount__c ta : taList) {
            	ta.Standers__c = cs.Id ;
            }
            insert taList;
            update tmp ; 
            backId = cs.Id ; 
            isSuccess = true ; 
            msg = '拆分成功!';
        }catch (Exception e) {

            Database.rollback(sp);
            isSuccess = false;

            msg = '拆分失败!'+e.getMessage() ;
        }
        



    }

    public class PolicyBean {
    	public String impId ; 
    	public String name ; //仪器名称
    	public Decimal num ; //拆分台数
    	public String brand ;//品牌
    	public String cate1 ; //一级分类
    	public String cate2 ; //二级分类
    	public Decimal total ; //总台数
    	public Decimal devNum ; //剩余台数
    	public Decimal coopyear ; //合作年限
    	public Decimal amount ; //年基本采购额 
    	public String startDate ; //合作开始日期

    	public Decimal subprofit ; 
    	public Decimal groupprofit ; 

    	public Decimal returnServiceFee;
    	public Decimal returnServiceFeeRentalFee;




    	public PolicyBean(InstrumentMarketingPolicy__c imp ){
    		impId = imp.Id ; 
    		name = imp.MarketingPolicy__r.Product__r.ProductName__c;
    		brand = imp.Brand__c;
    		cate1 = imp.Category1__c;
    		cate2 = imp.Category2__c;
    		total = imp.Quantity__c;
    		devNum = (imp.DevidedEquipNum__c == null ? 0 : imp.DevidedEquipNum__c);

    		coopyear = imp.CooperationPeriod__c;
    		amount = imp.AmountPurchased__c ; 

    		returnServiceFee = imp.ReturnServiceFee__c;
    		returnServiceFeeRentalFee = imp.ReturnServiceFeeRentalFee__c;

    		subprofit = 0 ; 
    		groupprofit = 0 ; 

    	}


    }


}